var chat=(function()
{

var messageField=null,secret=null,output;

var initContext=function()
{
    var scripts=document.getElementsByTagName("SCRIPT");
    var src,p,context;
    //console.group("initContext");
    for (var i=0; i < scripts.length; i++)
    {
        src=scripts[i].src;
        p=src.indexOf("://");
        if (p >= 0)
        {
            src=src.substring(src.indexOf("/", p+3));            
            //console.debug("cutting abs URL to %s", src); 
        }
        
        p=src.indexOf("/script/");
        if (p < 0)
        {
            //console.debug("not found"); 
            continue;
        }
        else
        {
            context=src.substring(0,p);
            break;
        }
    }
    if (!context)
    {
        //console.warn("Konnte contextPath nicht ermitteln");
    }
    else
    {
        ff.contextPath = context;
        //console.debug("ff.contextPath = %s", context);
    }
    //console.groupEnd();
};

var ns =
{
init:
    function()
    {
        var ctrlform = document.getElementById("ctrlform") || console.error("no #ctrlform");
        
        messageField = document.getElementById("messageField") || console.error("no #messageField");       
        var secretField = document.getElementById("secret") || console.error("no #secret");
        secret = secretField.value;
        output = document.getElementById("output") || console.error("no #output");
        
        ff.event.add(ctrlform,"submit",chat.onSendMessage);
        
        initContext();
        chat.request();        
    },
onSendMessage:
    function(ev)
    {
        try
        {
	        ff.request({
	            url: ff.contextPath+"/app/chat/hub/send",
	            params: { "secret" : secret, "msg" : messageField.value },
	            response: chat.onSendResponse });
        }
        catch(e)
        {
            log.error(e);
        }	            
        
        ff.event.preventDefault(ev);
    },
onSendResponse:
    function(response)
    {
        //console.debug("onSendResponse: %o", response.json());
        messageField.value="";
    },        
onReceiveResponse:
    function(response)
    {
        try
        {
            var messages = response.json();
            if (typeof messages.length != "undefined")
            {
	            for (var i=0; i < messages.length; i++)
	            {
                    chat.output(messages[i]);	                
	            }
	        }
        }
        catch(e)
        {
            console.error(e);
        }        
        chat.request();
    },
onError:
    function(response,e)
    {
        chat.output({"type":"ERROR","source":"system","message":e});
        chat.request();
    },
request:
    function()
    {
        ff.request({
            url: ff.contextPath+"/app/chat/hub/receive",
            params: { "secret" : secret },
            response: chat.onReceiveResponse, 
            error: chat.onError});
    },
colors:
    {},
color:
    function(s)
    {   
        var sum = chat.colors[s];
        if (!sum && sum !== 0)
        { 
	        var i=0;
	        sum = 0;
	        for (i=0;i<s.length;i++)
	        {
	            sum += s.charCodeAt(i);
	        }
	        sum = sum % 36;
	        chat.colors[s] = sum;
	    }
	    return sum;
    },
time:
    function()
    {
        var date = new Date();
        var hours = date.getHours();
        var minutes = date.getMinutes();
        
        if (hours < 10)
            hours = "0" + hours;
        if (minutes < 10)
            minutes = "0" + minutes;
            
      return hours+":"+minutes;
    
    },
output:
    function(message)
    {
        var type = message.type.toLowerCase();
        
        var color = chat.color(message.source);
        var time = chat.time();
        
        var nick = message.source;
        var pos = nick.indexOf("!");
        if (pos > 0)
        {
            if ( type == "privmsg")
            {
                nick = ">>"+nick.substring(0,pos)+"<<";
            }
            else
            {
                nick = "<"+nick.substring(0,pos)+">";
            }
        }
        
        if (type == "action")
        {
            output.appendChild(
                DIV({"class":"clearIE color"+color},
                    SPAN({"class":"time"},time),
                    SPAN({"class":"nick","title":message.source},"*"),
                    SPAN({"class":"message color"+color}, nick + " " + message.message)
                    ));
        }
        else if ( type == "info")
        {
            output.appendChild(
                DIV({"class":"clearIE color"+color},
                    SPAN({"class":"time"},time),
                    SPAN({"class":"nick","title":message.source},"-!-"),
                    SPAN({"class":"message color"+color}, nick + " " + message.message)
                    ));
        }
        else
        {
	        output.appendChild(
	            DIV({"class":"clearIE color"+color},
                    SPAN({"class":"time"},time),
	                SPAN({"class":"nick","title":message.source},nick),
	                SPAN({"class":"message color"+color}, message.message)
	                ));
        }       
    }
};

ff.dom.init(window);

ff.event.onload(ns.init);

return ns;
})();